﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Msg;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using Kingdee.K3.Core.MFG.SFC.Mobile.PlugIn;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace RCE.K3.YGJD.Service.PlugIn.SAL
{

    [HotUpdate]
    [Description("销售订单 保存校验库存")]
    public class SalOrderSaveCheckInvServicePlugIn : AbstractOperationServicePlugIn
    {
        public override void EndOperationTransaction(EndOperationTransactionArgs e)
        {
            base.EndOperationTransaction(e);
            IOperationResult result = new OperationResult();
            string message = "";
            foreach (var item in e.DataEntitys)
            {
                DynamicObjectCollection data = item["SaleOrderEntry"] as DynamicObjectCollection;                
                foreach (var itemEntry in data)
                {
                    try
                    {
                        string materialId = getBaseDataNumberId(itemEntry["MaterialId"] as DynamicObject);
                        string stockId = getBaseDataNumberId(itemEntry["SOStockId"] as DynamicObject);
                        string sql = $"select isnull(sum(FBASEQTY),0) FBASEQTY from T_STK_INVENTORY where FMATERIALID = '{materialId}' and FSTOCKID = '{stockId}' ";
                        string seq = itemEntry["Seq"].ToString();
                        var dataRows = DBUtils.ExecuteDynamicObject(this.Context, sql);
                        if (dataRows.Count <= 0)
                        {
                            result.OperateResult.Add(new OperateResult()
                            {
                                Name = $"第{seq}行，未查询到库存信息\r\n",
                                Message = "失败",
                                SuccessStatus = false,
                            });
                            message += $"第{seq}行，未查询到库存信息\r\n";
                            continue;
                        }

                        decimal invQty = Convert.ToDecimal(dataRows[0]["FBASEQTY"]);
                        decimal qty = Convert.ToDecimal(itemEntry["Qty"]);

                        if (invQty < qty)
                        {
                            result.OperateResult.Add(new OperateResult()
                            {
                                Name = $"第{seq}行，库存数量：{invQty.ToString("F3")} < 销售数量：{qty.ToString("F3")}\r\n",
                                Message = "失败",
                                SuccessStatus = false,
                            });
                            message += $"第{seq}行，库存数量：{invQty.ToString("F3")} < 销售数量：{qty.ToString("F3")}\r\n";
                            continue;
                        }
                    }
                    catch (Exception)
                    {

                    }
                }
            }
            if (result.OperateResult.Count > 0)
            {
                throw new Exception(message);
            }
        }


        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);
            e.FieldKeys.Add("FSEQ");
            e.FieldKeys.Add("FMATERIALID");
            e.FieldKeys.Add("FSOSTOCKID");
            e.FieldKeys.Add("FQTY");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dyobj"></param>
        /// <returns></returns>
        public string getBaseDataNumberId(DynamicObject dyobj)
        {
            if (dyobj == null)
            {
                return "";
            }
            string number = "";
            if (dyobj.DynamicObjectType.Properties.Contains("Id"))
            {
                number = dyobj["Id"].ToString();
            }
            return number;
        }


    }
}
